package app1.rapidsquare.com.core;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.classes.User;

/**
 * Created by Hikmat on 05.09.2014.
 */
public class Facebook {

    private UiLifecycleHelper uiHelper;
    private Activity mActivity;
    private boolean mIsProfile;
    private static final List<String> permissions = Arrays.asList(
            "user_about_me", "email", "user_birthday", "user_status",
            "user_location", "user_online_presence", "user_hometown",
            "user_photo_video_tags", "user_photos", "offline_access",
            "user_website");
    private ILoadComplete mILoadComplete;

    public Facebook(Activity activity, boolean isProfile, ILoadComplete iLoadComplete) {
        mActivity = activity;
        mIsProfile = isProfile;
        mILoadComplete = iLoadComplete;
    }

    public void onCreate(Bundle savedInstanceState) {
        uiHelper = new UiLifecycleHelper(mActivity, null);
        uiHelper.onCreate(savedInstanceState);
    }

    public void onResume() {
        uiHelper.onResume();
    }

    public void onPause() {
        uiHelper.onPause();
    }

    public void onStop() {
        uiHelper.onStop();
    }

    public void onDestroy() {
        uiHelper.onDestroy();
    }

    public void onSaveInstanceState(Bundle outState) {
        uiHelper.onSaveInstanceState(outState);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Session.getActiveSession() != null) {
            Session.getActiveSession().onActivityResult(mActivity, requestCode,
                    resultCode, data);
        }
    }

    public void RunFacebookLogin() {
        Session.openActiveSession(mActivity, true,
                permissions, callback);
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state,
                         Exception exception) {
            if (session.isOpened()) {
                SendRequestToFacebook(session);
            }
        }
    };

    private void SendRequestToFacebook(Session session) {

        Request uploadRequest = Request.newMeRequest(session,
                new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        DeserializeAndSave(user);
                    }
                });
        uploadRequest.executeAsync();
    }

    private void DeserializeAndSave(GraphUser user) {

        if (user != null) {
            try {

                JSONObject jsonObject = user.getInnerJSONObject();
                User profileData = new User();
                if (!mIsProfile) {
                    if (jsonObject.has("id"))
                        profileData.FacebookId = jsonObject.getString("id");
                    if (jsonObject.has("first_name"))
                        profileData.FirstName = jsonObject.getString("first_name");
                    if (jsonObject.has("last_name"))
                        profileData.LastName = jsonObject.getString("last_name");
                    if (jsonObject.has("email"))
                        profileData.Email = jsonObject.getString("email")
                                .replace('"', ' ').trim();
                    if (jsonObject.has("location")) {
                        JSONObject jLocationObject = new JSONObject(
                                jsonObject.getString("location"));
                        if (jLocationObject.has("name")) {
                            String locationName = jLocationObject.getString("name");
                            profileData.City = locationName.split(",")[0];
                            profileData.State = locationName.split(",")[0];
                        }
                    }

                    profileData.ImageUrl = String.format(Utility.FACEBOOK_PROFILE_PIC_URL_FORMAT, profileData.FacebookId);
                    profileData.SocialType = Utility.SocialType.Facebook.value;
                    profileData.FacebookName = profileData.FirstName + " " + profileData.LastName;

                } else {
                    if (jsonObject.has("id"))
                        profileData.FacebookId = jsonObject.getString("id");

                    String facebookName = "";

                    if (jsonObject.has("first_name"))
                        facebookName += jsonObject.getString("first_name");
                    if (jsonObject.has("last_name"))
                        facebookName += " " + jsonObject.getString("last_name");

                    profileData.FacebookName = facebookName;
                }

                mILoadComplete.onLoadComplete(profileData);

            } catch (Exception e) {
                Utility.Log("Facebook login deserialize", e);
            }
        }

    }
}
